package com.shd.edanpei.ui.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.shd.edanpei.R;
import com.shd.edanpei.base.data.RxBusCode;
import com.shd.edanpei.base.rxbus.RxBus;
import com.shd.edanpei.base.rxbus.Subscribe;
import com.shd.edanpei.db.DaoManager;
import com.shd.edanpei.enums.RoleEnum;
import com.shd.edanpei.util.DensityUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by mc on 2018/9/20.
 * 订单管理 顶部分类
 */

public class ManageTopView extends LinearLayout {

    //16：已创建，17：已审核，1：创建中，18：审核中，7：待确认，10：已撤销，3：待初审，4：待终审
    private final int[][] order2Types = {
            {0, 0, 1, 18, 7, 10},
            {1, 0, 3, 4, 7}};
    private final String[][] order2TypeNames = {
            {"我的订单", "全部", "待抢单", "审核中", "待确认", "撤销单"},
            {"共享订单", "全部", "待初审", "待终审", "待确认"}};

    private final Context mContext;
    private Listener listener;


    @BindView(R.id.allTop)
    View allTop;
    @BindView(R.id.rg_tab)
    RadioGroup radioGroup;
    @BindView(R.id.meTop)
    View meTop;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.rb_tab_left)
    RadioButton radioButtonLeft;
    @BindView(R.id.rb_tab_right)
    RadioButton radioButtonRight;
    Animation animation,animation2;

    private Unbinder mUnbinder;
    //订单1级类型
    private int mOrder1Type = -1;
    private PopupWindow window;

    public ManageTopView(Context context, Listener listener) {
        super(context);
        this.mContext = context;
        this.listener = listener;
        initView();
        initListener();
    }


    private void initView() {
        RxBus.get().register(this);
        LayoutInflater.from(mContext).inflate(R.layout.manage_new_top, this);
        mUnbinder = ButterKnife.bind(this);

        animation = AnimationUtils.loadAnimation(mContext,R.anim.readio_anim);
        animation2 = AnimationUtils.loadAnimation(mContext,R.anim.readio_anim2);
        int roleType = DaoManager.getInstance().getUserBean().getRoleType();

        if (roleType == RoleEnum.bank.getId()) {
            allTop.setVisibility(VISIBLE);
            meTop.setVisibility(GONE);
            initTab(1);
        } else {
            meTop.setVisibility(VISIBLE);
            allTop.setVisibility(GONE);
            initTab(0);
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                listener.refresh(mOrder1Type, order2Types[mOrder1Type][tab.getPosition() + 1]);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

//        getUnRead();
    }

    private void initListener() {
        radioButtonLeft.startAnimation(animation);
        radioButtonRight.startAnimation(animation2);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {
                    case R.id.rb_tab_left:
                        radioButtonLeft.startAnimation(animation);
                        radioButtonLeft.setTextColor(getResources().getColor(R.color.black));
                        radioButtonRight.startAnimation(animation2);
                        radioButtonRight.setTextColor(getResources().getColor(R.color.color_999999));
                        initTab(1);
                        break;
                    case R.id.rb_tab_right:
                        radioButtonRight.startAnimation(animation);
                        radioButtonRight.setTextColor(getResources().getColor(R.color.black));
                        radioButtonLeft.startAnimation(animation2);
                        radioButtonLeft.setTextColor(getResources().getColor(R.color.color_999999));
                        initTab(0);
                        break;
                    default:
                        break;
                }
            }
        });
    }


    private void initTab(final int orderType) {
        if (orderType == mOrder1Type) {
            //订单类型未修改，无需刷新
            return;
        }
        this.mOrder1Type = orderType;
        tabLayout.removeAllTabs();
        if (orderType == order2Types[0][0]) {
            //我的订单
            tabLayout.addTab(tabLayout.newTab().setText(order2TypeNames[0][1]));
            tabLayout.addTab(tabLayout.newTab().setText(order2TypeNames[0][2]));
            tabLayout.addTab(tabLayout.newTab().setText(order2TypeNames[0][3]));
            tabLayout.addTab(tabLayout.newTab().setText(order2TypeNames[0][4]));
            tabLayout.addTab(tabLayout.newTab().setText(order2TypeNames[0][5]));
        } else if (orderType == order2Types[1][0]) {
            //共享订单
            tabLayout.addTab(tabLayout.newTab().setText(order2TypeNames[1][1]));
            tabLayout.addTab(tabLayout.newTab().setText(order2TypeNames[1][2]));
            tabLayout.addTab(tabLayout.newTab().setText(order2TypeNames[1][3]));
            tabLayout.addTab(tabLayout.newTab().setText(order2TypeNames[1][4]));
        }

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

                    int magin = 0;
                    if (orderType == order2Types[0][0]) {
                        magin = DensityUtil.dp2px(tabLayout.getContext(), 10);
                    } else if (orderType == order2Types[1][0]) {
                        magin = DensityUtil.dp2px(tabLayout.getContext(), 20);
                    } else if (orderType == order2Types[2][0]) {
                        magin = DensityUtil.dp2px(tabLayout.getContext(), 40);
                    }

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LayoutParams params = (LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = magin;
                        params.rightMargin = magin;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
        tabLayout.getTabAt(order2Types[0][0]);
    }

//
//    @OnClick(R.id.headline)
//    void clickHeadline() {
//        int roleType = DaoManager.getInstance().getUserBean().getRoleType();
//        if (roleType == RoleEnum.bank.getId()) {
//            showPopWindow();
//        }
//    }

//    private void showPopWindow() {
//        if (window == null) {
//            View contentView = LayoutInflater.from(getContext()).inflate(R.layout.pop_order, null, false);
//            contentView.findViewById(R.id.view).setOnClickListener(new OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    window.dismiss();
//                }
//            });
//            final List<TextView> list = new ArrayList<>();
//            list.add((TextView) contentView.findViewById(R.id.tv_order1));
//            list.add((TextView) contentView.findViewById(R.id.tv_order2));
////            list.add((TextView) contentView.findViewById(R.id.tv_order3));
//            for (int i = 0; i < list.size(); i++) {
//                final int finalI = i;
//                list.get(i).setOnClickListener(new OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        for (int i1 = 0; i1 < list.size(); i1++) {
//                            //改变选中颜色
//                            list.get(i1).setTextColor(ContextCompat.getColor(getContext(), i1 == finalI ? R.color.main_color : R.color.black));
//                        }
////                        headline.setText(order2TypeNames[finalI][0]);
//                        initTab(finalI);
//                        window.dismiss();
//                    }
//                });
//            }
//            window = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
//            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//            window.setOutsideTouchable(true);
//            window.setTouchable(true);
//            window.setOnDismissListener(new PopupWindow.OnDismissListener() {
//                @Override
//                public void onDismiss() {
//                    //旋转0是复位ImageView
//                }
//            });
//        }
//        if (Build.VERSION.SDK_INT != 24) {
//            //只有24这个版本有问题，好像是源码的问题
//            window.showAsDropDown(viewTop, 0, 2);
//        } else {
//            //7.0 得这么写
//            int[] location = new int[2];
//            viewTop.getLocationOnScreen(location);
//            int x = location[0];
//            int y = location[1];
//            window.showAtLocation(viewTop, Gravity.NO_GRAVITY, 0, y + viewTop.getHeight() + 2);
//        }
//    }

    public interface Listener {
        void refresh(int order1Type, int order2Type);
    }

    @Subscribe(code = RxBusCode.CHECK_SHARE_ORDER)
    public void chechkShareOrder() {
        //共享订单
        radioGroup.check(R.id.rb_tab_left);
        initTab(1);
    }


}
